package master;

/**
 * 二进制求和
 *
 * @author chenyw
 * @date 2022/7/25 19:05
 */
public class M67addBinary {
    //竖式相加，重点在逢二进一
    public String addBinary(String a, String b) {
        int i = a.length() - 1;
        int j = b.length() - 1;
        int carry = 0;
        StringBuilder sb = new StringBuilder();
        while (i >= 0 && j >= 0) {
            int sum = carry;
            sum += a.charAt(i) - '0';
            sum += b.charAt(j) - '0';
            //处理进位情况
            carry = sum / 2;
            sb.append(sum % 2);
            i--;
            j--;
        }
        while (i >= 0) {
            int sum = a.charAt(i) - '0' + carry;
            carry = sum / 2;
            sb.append(sum % 2);
            i--;
        }
        while (j >= 0) {
            int sum = b.charAt(j) - '0' + carry;
            carry = sum / 2;
            sb.append(sum % 2);
            j--;
        }
        if (carry != 0) {
            sb.append(carry);
        }
        return sb.reverse().toString();
    }
}
